Working with Utility Classes from java.util in Java
Course: Core Java Training
Topic: Working with Utility Classes from java.util
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to the java.util Package
The java.util package is an important part of the Java Standard Library. It provides utility classes and interfaces that help developers store, organize, search, sort, process, and manipulate data efficiently. It also includes classes for generating random values, handling dates and times in legacy applications, processing tokens, and managing configuration properties.
Unlike the java.lang package, which is automatically available in Java source files, classes from java.util generally need to be imported before they can be referenced by their simple names.
Example: Importing a Utility Class
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
System.out.println(languages);
}
}
Output:
[Java, Python, JavaScript]
In this example, ArrayList is imported from java.util and used to store multiple strings in a resizable collection.
2. Learning Objectives
After completing this topic, you should be able to:
- Understand the purpose of the
java.util package.
- Use common collection classes such as
ArrayList, LinkedList, HashSet, and HashMap.
- Understand the difference between lists, sets, queues, and maps.
- Sort collections using
Collections and Comparator.
- Use the
Arrays utility class to manipulate arrays.
- Generate pseudorandom values with
Random.
- Use
Scanner to accept user input.
- Work with
Optional, Objects, and Properties.
- Choose suitable utility classes for practical Java applications.
3. Common Classes and Interfaces in java.util
| Class or Interface |
Purpose |
Example Use |
ArrayList |
Resizable list implementation |
Storing names or products |
LinkedList |
Linked implementation of list and deque |
Adding and removing elements at the ends |
HashSet |
Stores unique elements |
Removing duplicate values |
TreeSet |
Stores unique elements in sorted order |
Maintaining ordered unique values |
HashMap |
Stores key-value pairs |
Mapping IDs to employee names |
TreeMap |
Stores key-value pairs ordered by keys |
Maintaining sorted keys |
Queue |
Interface for elements waiting to be processed |
Task processing |
Collections |
Static utility methods for collections |
Sorting, reversing, and searching |
Arrays |
Static utility methods for arrays |
Sorting and searching arrays |
Comparator |
Defines custom ordering |
Sorting employees by salary |
Scanner |
Reads and parses input |
Accepting console input |
Random |
Generates pseudorandom values |
Simulations and simple random selection |
Optional |
Represents a value that may be absent |
Handling potentially missing results |
Objects |
Provides null-safe object utility methods |
Null checks and equality checks |
Properties |
Manages string-based configuration properties |
Application settings |
4. Understanding the Java Collections Framework
The Java Collections Framework provides interfaces and implementations for working with groups of objects. It helps developers store and process data without implementing common data structures from scratch.
Main Collection Types
| Type |
Characteristics |
Common Implementations |
| List |
Maintains a sequence, supports index-based access, and generally allows duplicates |
ArrayList, LinkedList |
| Set |
Does not allow duplicate elements according to its equality rules |
HashSet, LinkedHashSet, TreeSet |
| Queue |
Holds elements for processing, often in FIFO order |
PriorityQueue, LinkedList |
| Deque |
Supports insertion and removal at both ends |
ArrayDeque, LinkedList |
| Map |
Associates unique keys with values; it is not a subtype of Collection |
HashMap, LinkedHashMap, TreeMap |
Example: Using Different Collections
import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashMap;
public class CollectionDemo {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Aarav");
names.add("Priya");
names.add("Aarav");
HashSet<String> uniqueNames = new HashSet<>(names);
HashMap<Integer, String> students = new HashMap<>();
students.put(101, "Aarav");
students.put(102, "Priya");
System.out.println("List: " + names);
System.out.println("Unique names: " + uniqueNames);
System.out.println("Student 101: " + students.get(101));
}
}
Sample Output:
List: [Aarav, Priya, Aarav]
Unique names: [Aarav, Priya]
Student 101: Aarav
Note: The iteration order of a HashSet is not guaranteed, so the order of its elements may differ from the sample output.
5. Working with ArrayList
ArrayList is a resizable array implementation of the List interface. It is useful when an application needs an ordered collection that can grow or shrink dynamically.
Important ArrayList Methods
| Method |
Purpose |
add(element) |
Adds an element to the list. |
get(index) |
Retrieves an element by index. |
set(index, element) |
Replaces an element at a specified index. |
remove(index) |
Removes an element by index. |
remove(Object) |
Removes a matching element. |
size() |
Returns the number of elements. |
contains(element) |
Checks whether an element exists. |
clear() |
Removes all elements. |
Example: Managing a List of Courses
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> courses = new ArrayList<>();
courses.add("Core Java");
courses.add("SQL");
courses.add("Python");
System.out.println("First course: " + courses.get(0));
courses.set(1, "MySQL");
courses.remove("Python");
System.out.println("Updated courses: " + courses);
System.out.println("Total courses: " + courses.size());
}
}
Output:
First course: Core Java
Updated courses: [Core Java, MySQL]
Total courses: 2
When to Use ArrayList
- When indexed access is common.
- When elements need to be stored in a predictable sequence.
- When duplicates are allowed.
- When frequent insertions or removals in the middle are not the main workload.
6. Working with LinkedList
LinkedList implements both List and Deque. It can be used as a list or as a double-ended queue. It provides methods to add and remove elements at the beginning and end.
Example
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<String> tasks = new LinkedList<>();
tasks.add("Read");
tasks.add("Practice");
tasks.addFirst("Plan");
tasks.addLast("Review");
System.out.println(tasks);
tasks.removeFirst();
tasks.removeLast();
System.out.println(tasks);
}
}
Output:
[Plan, Read, Practice, Review]
[Read, Practice]
Important: Although LinkedList supports efficient operations at its ends, accessing an element by index generally requires traversing the list. For many general-purpose list operations, ArrayList is often a suitable default.
7. Working with HashSet and TreeSet
A Set stores unique elements. It is useful for removing duplicates and checking whether a value is already present.
HashSet
HashSet stores unique elements and does not guarantee iteration order.
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
HashSet<String> cities = new HashSet<>();
cities.add("Mumbai");
cities.add("Pune");
cities.add("Mumbai");
System.out.println(cities);
System.out.println("Contains Pune: " + cities.contains("Pune"));
}
}
The set contains only one occurrence of Mumbai. The displayed order is not guaranteed.
TreeSet
TreeSet stores unique elements in sorted order according to their natural ordering or a supplied comparator.
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(40);
numbers.add(10);
numbers.add(30);
numbers.add(10);
System.out.println(numbers);
}
}
Output:
[10, 30, 40]
HashSet vs TreeSet
| Feature |
HashSet |
TreeSet |
| Duplicates |
Not allowed |
Not allowed |
| Iteration order |
Not guaranteed |
Sorted order |
| Typical performance |
Average constant-time basic operations with good hash distribution |
Logarithmic-time basic operations |
| Best use |
Fast membership checks without ordering requirements |
Unique values that must remain sorted |
8. Working with HashMap
HashMap stores data as key-value pairs. Each key is unique, while multiple keys may refer to equal values. It is useful for looking up information by an identifier.
Common HashMap Methods
| Method |
Purpose |
put(key, value) |
Adds a mapping or replaces the value for an existing key. |
get(key) |
Returns the value for a key, or null if no mapping exists. |
getOrDefault(key, defaultValue) |
Returns the value or a specified default. |
containsKey(key) |
Checks whether a key is present. |
remove(key) |
Removes a mapping. |
keySet() |
Returns a set view of the keys. |
values() |
Returns a collection view of the values. |
entrySet() |
Returns a set view of key-value entries. |
Example: Employee Directory
import java.util.HashMap;
import java.util.Map;
public class EmployeeDirectory {
public static void main(String[] args) {
Map<Integer, String> employees = new HashMap<>();
employees.put(201, "Neha");
employees.put(202, "Rahul");
employees.put(203, "Amit");
System.out.println(employees.get(202));
for (Map.Entry<Integer, String> entry : employees.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
Explanation: The value associated with employee ID 202 is retrieved using get(). The loop visits the map entries, but their order is not guaranteed for a HashMap.
9. Understanding Queue and Deque
A Queue holds elements that are waiting to be processed. Many queues follow first-in, first-out (FIFO) ordering. A Deque, or double-ended queue, supports insertion and removal at both ends.
Example: Using ArrayDeque as a Queue
import java.util.ArrayDeque;
import java.util.Queue;
public class QueueDemo {
public static void main(String[] args) {
Queue<String> queue = new ArrayDeque<>();
queue.offer("Task 1");
queue.offer("Task 2");
queue.offer("Task 3");
System.out.println("Next task: " + queue.peek());
System.out.println("Processed: " + queue.poll());
System.out.println("Remaining: " + queue);
}
}
Output:
Next task: Task 1
Processed: Task 1
Remaining: [Task 2, Task 3]
Important Queue Methods
offer() attempts to add an element.
peek() examines the next element without removing it.
poll() retrieves and removes the next element, returning null if the queue is empty.
remove() retrieves and removes the next element but throws an exception if the queue is empty.
Note: ArrayDeque does not permit null elements. For concurrent producer-consumer applications, consider suitable classes from java.util.concurrent.
10. Using the Collections Utility Class
The Collections class contains static utility methods that operate on collections. It can sort, reverse, shuffle, search, find minimum and maximum values, and create certain wrappers around collections.
Common Collections Methods
| Method |
Purpose |
Collections.sort(list) |
Sorts a list using natural ordering. |
Collections.reverse(list) |
Reverses the current list order. |
Collections.shuffle(list) |
Randomly permutes a list. |
Collections.max(collection) |
Returns the maximum element. |
Collections.min(collection) |
Returns the minimum element. |
Collections.frequency(collection, value) |
Counts occurrences of a value. |
Collections.binarySearch(list, key) |
Searches a sorted list using binary search. |
Example: Sorting and Searching
import java.util.ArrayList;
import java.util.Collections;
public class CollectionsDemo {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(50);
numbers.add(10);
numbers.add(40);
numbers.add(20);
Collections.sort(numbers);
System.out.println("Sorted: " + numbers);
System.out.println("Minimum: " + Collections.min(numbers));
System.out.println("Maximum: " + Collections.max(numbers));
int index = Collections.binarySearch(numbers, 40);
System.out.println("Index of 40: " + index);
Collections.reverse(numbers);
System.out.println("Reversed: " + numbers);
}
}
Output:
Sorted: [10, 20, 40, 50]
Minimum: 10
Maximum: 50
Index of 40: 2
Reversed: [50, 40, 20, 10]
Important: Binary search requires the list to be sorted according to the same ordering used for the search. If the list is not sorted correctly, the result may be incorrect.
11. Using Comparator for Custom Sorting
The Comparator interface allows you to define a custom ordering for objects. It is useful when a class has several meaningful sorting criteria, such as sorting employees by salary, name, or ID.
Example: Sorting Employees by Salary
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class Employee {
String name;
double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return name + " - " + salary;
}
}
public class ComparatorDemo {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("Neha", 45000));
employees.add(new Employee("Amit", 35000));
employees.add(new Employee("Rahul", 55000));
employees.sort(Comparator.comparingDouble(e -> e.salary));
employees.forEach(System.out::println);
}
}
Output:
Amit - 35000.0
Neha - 45000.0
Rahul - 55000.0
To sort in descending salary order, use Comparator.comparingDouble((Employee e) -> e.salary).reversed().
12. Working with the Arrays Utility Class
The Arrays class contains static methods for manipulating arrays. It supports sorting, searching, filling, comparing, copying, and converting arrays into list views.
Common Arrays Methods
| Method |
Purpose |
Arrays.sort(array) |
Sorts an array. |
Arrays.binarySearch(array, key) |
Searches a sorted array. |
Arrays.toString(array) |
Returns a readable representation of a one-dimensional array. |
Arrays.equals(a, b) |
Compares array contents for equality. |
Arrays.fill(array, value) |
Fills array elements with a value. |
Arrays.copyOf(array, length) |
Copies an array to a specified length. |
Arrays.asList(values) |
Creates a fixed-size list backed by the supplied object array or varargs elements. |
Example: Array Operations
import java.util.Arrays;
public class ArraysDemo {
public static void main(String[] args) {
int[] numbers = {40, 10, 30, 20};
Arrays.sort(numbers);
System.out.println("Sorted: " + Arrays.toString(numbers));
int index = Arrays.binarySearch(numbers, 30);
System.out.println("Index of 30: " + index);
int[] copy = Arrays.copyOf(numbers, numbers.length);
System.out.println("Arrays equal: " + Arrays.equals(numbers, copy));
}
}
Output:
Sorted: [10, 20, 30, 40]
Index of 30: 2
Arrays equal: true
Important: Sort an array before using Arrays.binarySearch(). Also, the list returned by Arrays.asList() has a fixed size: you can replace existing elements, but cannot add or remove elements. To create a resizable list, use new ArrayList<>(Arrays.asList(values)).
13. Using Scanner for User Input
The Scanner class can parse primitive values and strings from console input, files, or other input sources. It is commonly used in beginner-level Java programs.
Common Scanner Methods
next() reads the next token.
nextLine() reads the remaining line.
nextInt() reads an integer token.
nextDouble() reads a double token.
hasNextInt() checks whether the next token can be read as an integer.
close() closes the scanner and its underlying source if that source is closeable.
Example: Reading Student Details
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
scanner.close();
}
}
Sample Input:
Enter your name: Priya Sharma
Enter your age: 22
Sample Output:
Name: Priya Sharma
Age: 22
Common issue: When calling nextLine() immediately after nextInt() or another token-reading method, the line separator may remain unread. Consume the remaining line before reading the next full line.
14. Generating Random Values with Random
The Random class generates pseudorandom values. It supports integers, long values, booleans, floating-point values, and streams of pseudorandom numbers.
Example
import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
Random random = new Random();
int number = random.nextInt(100);
boolean flag = random.nextBoolean();
System.out.println("Random number from 0 to 99: " + number);
System.out.println("Random boolean: " + flag);
}
}
The output varies between executions.
Generating a Value Within a Range
Random random = new Random();
int minimum = 10;
int maximum = 20;
int value = random.nextInt(maximum - minimum + 1) + minimum;
System.out.println(value);
This example generates an integer from 10 through 20, inclusive.
Security note: Use java.security.SecureRandom for security-sensitive tasks such as generating tokens. The ordinary Random class is not designed for cryptographic security.
15. Using Optional to Represent Missing Values
Optional represents a value that may or may not be present. It can make the absence of a result explicit and reduce accidental null handling in APIs that choose to use it.
Important Optional Methods
| Method |
Purpose |
Optional.of(value) |
Creates an Optional containing a non-null value. |
Optional.ofNullable(value) |
Creates an Optional that may be empty if the value is null. |
Optional.empty() |
Creates an empty Optional. |
isPresent() |
Checks whether a value is present. |
orElse(defaultValue) |
Returns the value or a default value. |
orElseGet(supplier) |
Returns the value or obtains a default from a supplier. |
ifPresent(action) |
Runs an action when a value is present. |
map(function) |
Transforms a present value. |
Example
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = null;
Optional<String> optionalEmail = Optional.ofNullable(email);
String result = optionalEmail.orElse("No email available");
System.out.println(result);
Optional<String> username = Optional.of("priya");
username.map(String::toUpperCase)
.ifPresent(System.out::println);
}
}
Output:
No email available
PRIYA
Best practice: Avoid calling get() without checking whether the Optional contains a value. Use methods such as orElse(), orElseGet(), map(), and ifPresent() when appropriate.
16. Using Objects Utility Methods
The Objects class provides static methods that simplify common operations on objects, especially null checks and equality comparisons.
Common Methods
Objects.equals(a, b) compares two references safely, including when either is null.
Objects.isNull(value) checks whether a reference is null.
Objects.nonNull(value) checks whether a reference is not null.
Objects.requireNonNull(value) throws NullPointerException if the value is null.
Objects.toString(value, defaultValue) returns a string representation or a default for a null reference.
Example
import java.util.Objects;
public class ObjectsDemo {
public static void main(String[] args) {
String first = null;
String second = "Java";
System.out.println(Objects.equals(first, second));
System.out.println(Objects.isNull(first));
System.out.println(Objects.nonNull(second));
System.out.println(Objects.toString(first, "Unknown"));
}
}
Output:
false
true
true
Unknown
Objects.requireNonNull() is especially useful for validating method arguments at the beginning of a method.
17. Working with Properties
The Properties class stores configuration information as string-based key-value pairs. It is commonly used for application settings, such as language preferences, server names, and feature configuration.
Example: Storing and Reading Properties
import java.util.Properties;
public class PropertiesDemo {
public static void main(String[] args) {
Properties settings = new Properties();
settings.setProperty("app.name", "StudentPortal");
settings.setProperty("app.version", "1.0");
System.out.println(settings.getProperty("app.name"));
System.out.println(settings.getProperty("app.version"));
System.out.println(settings.getProperty("app.theme", "light"));
}
}
Output:
StudentPortal
1.0
light
The third call uses a default value because app.theme has not been defined.
Important Points
- Use
setProperty() to store string values.
- Use
getProperty() to retrieve a property.
- Use the overload with a default value when a property may be absent.
- Properties can be loaded from or stored to streams using appropriate methods.
- Do not store passwords or other secrets in plain-text configuration files without an appropriate security design.
18. Using Date and Calendar in Legacy Java Code
The java.util package includes older date and time classes such as Date and Calendar. You may encounter these classes in existing Java applications and older APIs.
Example: Current Date and Time
import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
Date currentDate = new Date();
System.out.println(currentDate);
}
}
The displayed date and time depend on the system clock and environment.
Modern recommendation: For most new Java date and time code, prefer the java.time package, which provides types such as LocalDate, LocalTime, LocalDateTime, Instant, and ZonedDateTime. These APIs offer clearer types for dates, times, instants, and time zones.
19. Choosing the Right Utility Class
| Requirement |
Recommended Choice |
Reason |
| Store an ordered group with duplicates |
ArrayList |
Supports indexed access and dynamic sizing. |
| Store unique values without requiring order |
HashSet |
Prevents duplicates and supports efficient membership checks. |
| Store unique values in sorted order |
TreeSet |
Keeps elements ordered. |
| Look up values by a key |
HashMap |
Provides key-value mappings. |
| Sort or reverse a list |
Collections |
Offers common collection algorithms. |
| Sort or search an array |
Arrays |
Provides array-focused utility methods. |
| Accept console input |
Scanner |
Parses input tokens and values. |
| Generate ordinary pseudorandom values |
Random |
Supports common random operations. |
| Represent a potentially missing result |
Optional |
Makes value absence explicit in an API. |
| Manage string-based settings |
Properties |
Stores named configuration values. |
20. Common Mistakes and Troubleshooting
| Problem |
Reason |
Solution |
| Class not found during compilation |
The class may not be imported or referenced correctly. |
Add the required import or use its fully qualified name. |
| Unexpected HashSet order |
HashSet does not guarantee iteration order. |
Use TreeSet for sorted order or LinkedHashSet for insertion order. |
| Duplicate values appear in a list |
Lists generally permit duplicates. |
Use a set if uniqueness is required. |
| HashMap lookup returns null |
The key may be missing, or it may map to null. |
Use containsKey() when the distinction matters. |
| Binary search returns an unexpected index |
The array or list may not be sorted using the required ordering. |
Sort first using the same ordering. |
| Cannot add to a list created with Arrays.asList() |
The returned list has a fixed size. |
Wrap it in a new ArrayList for resizing. |
| Scanner reads an empty line |
A previous token-reading call may leave the line separator unread. |
Consume the remaining line before reading the next full line. |
| Number input causes an exception |
The input token may not be a valid number. |
Validate input or catch the appropriate parsing exception. |
| Optional.get() throws an exception |
The Optional is empty. |
Use a safe fallback or check presence before accessing the value. |
21. Best Practices for Using java.util
- Choose collection implementations based on the application's access patterns and ordering requirements.
- Use generics, such as
List<String>, to improve type safety.
- Use the
List, Set, Queue, and Map interfaces where possible so implementations can be changed more easily.
- Do not rely on the iteration order of
HashMap or HashSet.
- Use
Collections.sort() or List.sort() when sorting is required.
- Ensure that data is sorted before using binary search.
- Use
Scanner carefully when reading mixed token and line input.
- Do not use
Random for cryptographic or security-sensitive values.
- Use
Optional where it improves API clarity, rather than wrapping every variable unnecessarily.
- Prefer
java.time over legacy date and calendar APIs for new date and time code.
- Use concurrent collections or appropriate synchronization when shared data must be accessed safely by multiple threads.
22. Practice Exercises
- ArrayList Exercise: Create a list of five programming languages, replace one item, and remove another.
- HashSet Exercise: Store ten integers in a set and display the unique values.
- TreeSet Exercise: Store numbers in a
TreeSet and display them in ascending order.
- HashMap Exercise: Create a student directory using roll numbers as keys and student names as values.
- Collections Exercise: Sort a list of integers and find its minimum and maximum values.
- Arrays Exercise: Sort an integer array and search for a particular value using binary search.
- Comparator Exercise: Create an employee class and sort employees by salary, then by name.
- Scanner Exercise: Accept a user's name, age, and city and print a formatted summary.
- Random Exercise: Simulate rolling a six-sided die using a pseudorandom integer.
- Optional Exercise: Create a method that returns an Optional value when a user record is found.
- Properties Exercise: Store application name and version settings and read them back.
23. Mini Project: Student Management Utility
Objective: Build a small console-based student management program using classes from java.util.
Project Requirements
- Store student names in an
ArrayList.
- Use a
HashSet to identify unique student names.
- Use a
HashMap to associate student IDs with names.
- Sort the student list alphabetically using
Collections.sort().
- Accept input using
Scanner.
- Display the total number of students and their details.
- Validate input and handle unexpected values appropriately.
Sample Implementation
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class StudentManagement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> names = new ArrayList<>();
Map<Integer, String> students = new HashMap<>();
System.out.print("Enter number of students: ");
int count = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < count; i++) {
System.out.print("Enter student ID: ");
int id = Integer.parseInt(scanner.nextLine());
System.out.print("Enter student name: ");
String name = scanner.nextLine().strip();
students.put(id, name);
names.add(name);
}
Collections.sort(names);
Set<String> uniqueNames = new HashSet<>(names);
System.out.println("Sorted names: " + names);
System.out.println("Unique names: " + uniqueNames);
System.out.println("Student records:");
for (Map.Entry<Integer, String> entry : students.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
scanner.close();
}
}
Project Notes: This example demonstrates basic collection operations. A production version should validate the student count and IDs, handle duplicate IDs according to a clear rule, and handle invalid numeric input. The order of entries in the HashMap and elements in the HashSet is not guaranteed.
24. Interview Questions and Answers
Q1. What is the java.util package?
Answer: It is a Java package that provides collection classes, utility methods, input handling, random number generation, configuration properties, and other useful utilities.
Q2. What is the difference between List and Set?
Answer: A list is an ordered sequence that can contain duplicates, while a set represents unique elements and does not permit duplicates according to its equality rules.
Q3. What is the difference between ArrayList and LinkedList?
Answer: ArrayList is backed by a resizable array and generally provides fast indexed access. LinkedList is linked and supports efficient operations at its ends, but indexed access requires traversal.
Q4. What is the difference between HashSet and TreeSet?
Answer: HashSet does not guarantee iteration order. TreeSet maintains elements in sorted order.
Q5. What is a HashMap?
Answer: It is a map implementation that stores key-value pairs. Keys are unique, and a later mapping for an existing key replaces its previous value.
Q6. Is Map part of the Collection interface hierarchy?
Answer: No. Map is a separate interface in the Collections Framework. It stores key-value associations rather than individual collection elements.
Q7. What is the purpose of the Collections class?
Answer: It provides static utility methods for working with collections, including sorting, reversing, shuffling, and finding minimum or maximum elements.
Q8. What is the difference between Arrays and Collections?
Answer: Arrays provides utility methods for arrays, while Collections provides utility methods for collection objects such as lists and sets.
Q9. Why must a list be sorted before binary search?
Answer: Binary search relies on ordered data. Searching an unsorted list can produce an incorrect result.
Q10. What is the purpose of Comparator?
Answer: Comparator defines a custom ordering for objects and allows sorting by different fields or rules.
Q11. What is Optional used for?
Answer: It represents a value that may be absent, making that possibility explicit in an API and offering methods to handle it safely.
Q12. What is the difference between Random and SecureRandom?
Answer: Random generates ordinary pseudorandom values. SecureRandom is designed to provide cryptographically strong random values for security-sensitive tasks.
Q13. What is Scanner used for?
Answer: It reads and parses input from sources such as the console, files, or strings.
Q14. What is Properties used for?
Answer: It stores and retrieves string-based key-value configuration settings.
Q15. Why are generics useful in collections?
Answer: Generics provide compile-time type safety, reduce the need for manual casts, and make code easier to understand.
25. Quick Revision Checklist
- Understand the purpose of
java.util.
- Know the difference between lists, sets, queues, deques, and maps.
- Practice adding, retrieving, updating, and removing collection elements.
- Remember that
HashSet and HashMap do not guarantee iteration order.
- Understand when to use
TreeSet and TreeMap.
- Use
Collections for collection operations and Arrays for array operations.
- Use
Comparator to define custom ordering.
- Understand the difference between
Scanner.next() and Scanner.nextLine().
- Use
Random for ordinary pseudorandom values and SecureRandom for security-sensitive values.
- Know how
Optional, Objects, and Properties simplify common programming tasks.
- Prefer
java.time for new date and time code.
26. Conclusion
The java.util package is essential for everyday Java programming. Its collection classes make it easier to store and organize data, while utility classes such as Collections, Arrays, Scanner, Random, Optional, Objects, and Properties simplify many common tasks.
Understanding the strengths and limitations of these classes helps you select appropriate data structures, write type-safe programs, process input, sort and search information, and build maintainable Java applications. Practice the examples and mini project to strengthen your understanding of utility classes from java.util.
Continue Learning: Explore the Core Java Training Course, register for a course demo, or visit the JustAcademy website.